package com.ww.controller;


import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.PageInfo;
import com.ww.common.R;
import com.ww.entity.WallpaperDownload;
import com.ww.pojo.Wallpaper;
import com.ww.pojo.WallpaperComment;
import com.ww.pojo.WallpaperVO;
import com.ww.service.WallpaperDownloadService;
import com.ww.service.WallpaperService;
import org.apache.commons.io.FileUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

/**
 * (Wallpaper)表控制层
 *
 * @author makejava
 * @since 2022-05-18 17:34:12
 */
@Controller
@RequestMapping("wallpaper")
public class WallpaperController {
    /**
     * 服务对象
     */
    @Resource
    private WallpaperService wallpaperService;

    @Resource
    private WallpaperDownloadService wallpaperDownloadService;


    /**
     * 分页查询
     * @param pageNum
     * @return
     */
    @RequestMapping(value = "/wallpaperpage")
    public String wallpaperpage(@RequestParam(value = "setPageNum",defaultValue = "1") String pageNum,
                                Model model){
        PageInfo<Wallpaper> wallpaperpage=wallpaperService.wallpaperpage(Integer.valueOf(pageNum),5);
        model.addAttribute("wallpaperpage",wallpaperpage);
        return "admin/examples/wallpaper";
    }

    /**
     * 分页查询（未审核）
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping(value = "/wallpaperpageBystate")
    public String wallpaperpageBystate(@RequestParam(value = "setPageNum",defaultValue = "1") String pageNum,
                                       Model model){
        PageInfo<Wallpaper> wallpaperpage=wallpaperService.wallpaperpageBystate(Integer.valueOf(pageNum),5);
        model.addAttribute("wallpaperpage",wallpaperpage);
        return "admin/examples/wallpaper_examine";
    }


    /**
     * 分页查询（审核通过）
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping(value = "/wallpaperpageByTG")
    public String wallpaperpageByTG(@RequestParam(value = "setPageNum",defaultValue = "1") String pageNum,
                                    Model model){
        PageInfo<Wallpaper> wallpaperpage=wallpaperService.wallpaperpageByTG(Integer.valueOf(pageNum),6);
        model.addAttribute("wallpaperpage",wallpaperpage);
        return "wallpaper_main";
    }

    /**
     * 分页查询（条件）
     * @param condition
     * @param model
     * @return
     */
    @RequestMapping("/wallpaperpagevague")
    public String wallpaperselectvague(@RequestParam(value = "condition",defaultValue = "") String condition,
                                       Model model){
        PageInfo<Wallpaper> wallpaperpage=wallpaperService.wallpaperpagevague(1,condition,5000);
        model.addAttribute("wallpaperpage",wallpaperpage);
        return "wallpaper_main";
    }


    /**
     * 分页查询
     *
     * @param wallpaper   筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Wallpaper>> queryByPage(Wallpaper wallpaper,
                                                       PageRequest pageRequest) {
        return ResponseEntity.ok(this.wallpaperService.queryByPage(wallpaper, pageRequest));
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Wallpaper> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.wallpaperService.queryById(id));
    }

    /**
     * 通过主键查询壁纸详情
     * @param wallpaperId
     * @return
     */
    @RequestMapping("selectwallpaperVo")
    public String selectwallpaperVo(@RequestParam(value = "wallpaperId") Integer wallpaperId,
                                    Model model){
        WallpaperVO wallpaperVO = this.wallpaperService.selectbyid(wallpaperId);
        model.addAttribute("wallpaperVO",wallpaperVO);
        return "wallpaper_details";
    }

    /**
     * 新增数据
     *
     * @param wallpaperVO 实体
     * @return 新增结果
     */
    @ResponseBody
    @PostMapping
    public String add(@RequestBody WallpaperVO wallpaperVO, HttpSession httpSession) {
        if (httpSession.getAttribute("userId")==null){
            return "请先登录";
        }else {
            this.wallpaperService.insert(wallpaperVO,httpSession);
            return "上传成功";
        }
    }

    @RequestMapping("/comment")
    @ResponseBody
    public R insertComment(@RequestBody WallpaperComment wallpaperComment, HttpSession httpSession){
        System.out.println("wallpaperComment = " + wallpaperComment);
        if (httpSession.getAttribute("userId")==null){
            System.out.println("wallpaperComment = " + wallpaperComment);
            return R.fail();
        }else{
            this.wallpaperService.insertcomment(wallpaperComment,httpSession);
            return R.success();
        }
    }


    @RequestMapping("/updatawallpaper1")
    @ResponseBody
    public Wallpaper updatewallpaper(@RequestBody Wallpaper wallpaper){
        //System.out.println(wallpaper);
        wallpaperService.update(wallpaper);
        return wallpaper;
    }

    @RequestMapping("/updatewallpaper")
    @ResponseBody
    public Wallpaper edit(@RequestParam(value = "wallpaperId") String wallpaperId,
                       @RequestParam(value = "wallpaperName",required = false) String wallpaperName,
                       @RequestParam(value = "wallpaperUrl",required = false) String wallpaperUrl,
                       @RequestParam(value = "pagenum",defaultValue = "1") String pagenum) {
        System.out.println("id = " + wallpaperId);
        System.out.println("name = " + wallpaperName);
        System.out.println("url = " +wallpaperUrl);
        System.out.println("pagenum = " + pagenum);
        Wallpaper wallpaper1 =new Wallpaper();
        wallpaper1.setWallpaperId(Integer.parseInt(wallpaperId));
        wallpaper1.setWallpaperName(wallpaperName);
        wallpaper1.setWallpaperUrl(wallpaperUrl);
        System.out.println("成功修改ID为"+wallpaperId+"的壁纸");
        wallpaperService.update(wallpaper1);
        return wallpaper1;
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @RequestMapping("/deletewallpaper")
    public String deleteById(@RequestParam(value = "id") String id,
                             @RequestParam(value = "pagenum") String pagenum,
                             Model model) {
        wallpaperService.deleteById(Integer.valueOf(id));
        System.out.println("删除ID为"+id+"的壁纸");
        PageInfo<Wallpaper> wallpaperpage=wallpaperService.wallpaperpage(Integer.valueOf(pagenum),5);
        model.addAttribute("wallpaperpage",wallpaperpage);
        return "admin/examples/wallpaper";
    }

    /**
     * 下载壁纸
     * @param wallpaperDownload
     * @return
     */
    @RequestMapping("/downloadwallpaper")
    public ResponseEntity<byte[]> downloadwallpaper(@RequestBody WallpaperDownload wallpaperDownload,HttpSession httpSession){
        Wallpaper wallpaper;
        wallpaper=this.wallpaperService.queryById(wallpaperDownload.getWallpaperId());
        String pageUrl=wallpaper.getWallpaperUrl();
        wallpaperDownload.setWallpaperId(wallpaper.getWallpaperId());
        wallpaperDownload.setDownloadTime(new Date());
        if (httpSession.getAttribute("userId")!=null){
        wallpaperDownload.setUserId(Integer.parseInt(httpSession.getAttribute("userId").toString()));}
        else{
            wallpaperDownload.setUserId(0);
        }
        this.wallpaperDownloadService.insert(wallpaperDownload);
        try (InputStream in = new URL(pageUrl).openConnection().getInputStream()){
            File tempFile = FileUtil.createTempFile(null);
            FileUtils.copyInputStreamToFile(in, tempFile);
            byte[] bytes = FileUtils.readFileToByteArray(tempFile);
            HttpHeaders headers=new HttpHeaders();
            String content_type=new URL(pageUrl).openConnection().getContentType();
            // Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名。
            headers.set("Content-Disposition","attachment;filename="+ URLEncoder.encode(wallpaper.getWallpaperName(), "UTF-8"));
            headers.set("charsetEncoding","utf-8");
            //headers.set("content-type","multipart/form-data");
            headers.set("content-type",content_type);
            ResponseEntity<byte[]> entity=new ResponseEntity<>(bytes,headers, HttpStatus.OK);
            FileUtil.del(tempFile);
            return entity;
        }catch (IOException e){
            System.out.println(("读取失败:" + e.getMessage()));
            e.printStackTrace();
            return null;
        }
    }

    //输出下载记录
    //@RequestMapping("selectalldownload")
    //public void wallpaperDownload(){
    //    System.out.println(wallpaperDownloadService.selectAll());
    //}

    /**
     * 虚假的统计页
     * @return
     */
    @RequestMapping("/main")
    public String main(){
        return "admin/examples/main";
    }

    /**
     * 虚假的消息页
     * @return
     */
    @RequestMapping("/message")
    public String message(){
        return "admin/examples/message";
    }


    //@RequestMapping("ttt")
    //@ResponseBody
    //public void test(){
    //    this.wallpaperService.testinsert();
    //}
}

